/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AlgoritmosPanel.java
 *
 * Created on 30-abr-2011, 17:32:17
 */

package ia_psr.transportesGUI;

import ia_psr.PSRSolver;
import ia_psr.algoritmos.*;
import ia_psr.builder.GrafoEmpresaTransportesBuilder;
import ia_psr.graph.GrafoEmpresaTransportes;
import ia_psr.problemas.transportes.EmpresaTransportes;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import ia_psr.graph.Tarea;

/**
 *
 * @author Rubén Avalos Elvira y Fabiana Celiberti Tapie
 */
import javax.swing.JFrame;
public class AlgoritmosPanel extends javax.swing.JPanel {
    private JFrame parent;

    /** Creates new form AlgoritmosPanel */
    public AlgoritmosPanel(JFrame parent) {
        this.parent = parent;
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bgAlgoritmos = new javax.swing.ButtonGroup();
        btnIniciar = new javax.swing.JButton();
        cbAlgoritmos = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Algoritmo", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(102, 102, 102))); // NOI18N

        btnIniciar.setText("Iniciar");
        btnIniciar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                btnIniciarMouseReleased(evt);
            }
        });

        cbAlgoritmos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Primero en profundidad", "MVR con comprobación hacia delante", "Grado heurístico", "Consistencia de arco", "MVR + grado heurístico", "MVR + GH + consistencia de arco" }));
        cbAlgoritmos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                cbAlgoritmosMouseReleased(evt);
            }
        });

        jLabel1.setText("Seleccionar:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbAlgoritmos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnIniciar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cbAlgoritmos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnIniciar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void cbAlgoritmosMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cbAlgoritmosMouseReleased

    }//GEN-LAST:event_cbAlgoritmosMouseReleased

    private void btnIniciarMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnIniciarMouseReleased
        try {
            // limpiar datos anteriores
            ((TransportesFrame)parent).clearPlanningData();

            // grafo
            GrafoEmpresaTransportes g =
                    (GrafoEmpresaTransportes)GrafoEmpresaTransportesBuilder.getInstance().getBuildedGraph();

            // problema
            EmpresaTransportes et = EmpresaTransportes.getInstance();

            if (g.getNodos().isEmpty() || et.elementos.isEmpty())
                throw new Exception();

            // Determinamos el algoritmo
            IAlgoritmo a;
            String nombreAlgoritmo = cbAlgoritmos.getSelectedItem().toString();
            if (nombreAlgoritmo.equals("Primero en profundidad")) {
                a = new PSRBacktracking();

            } else if (nombreAlgoritmo.equals("MVR con comprobación hacia delante")) {
                a = new PSRMinimoValorRestante();

            } else if (nombreAlgoritmo.equals("Grado heurístico")) {
                a = new PSRGradoHeuristico();

            } else if (nombreAlgoritmo.equals("Consistencia de arco")) {
                a = new PSRConsistenciaArco();

            } else if (nombreAlgoritmo.equals("MVR + grado heurístico")) {
                a = new PSRMVR_GH();

            } else { // if (nombreAlgoritmo.equals("MVR + GH + CA")) {
                a = new PSRMVR_GH_CA();
            }

            PSRSolver s = PSRSolver.getInstance();
            s.initSolver(g, et, et, a);

            boolean planificacionReducida = false;
            LinkedList<Tarea> tareasEliminadas = new LinkedList<Tarea>();
            Tarea t;

            s.solve();

            // Eliminamos tareas no programadas hasta que quede un horario realizable
            double tiempoEjecucion = a.getExecutionTime();
            int nodosExpandidos = a.getNodosExpandidos();
            int variablesExpandidas = a.getVariablesExpandidas();
            while (!s.hasSolution() && g.hayTareasNoProgramadas()) {
                t = g.removeLargestTareaNoProgramada();
                if (t.duracion() != -1)
                    tareasEliminadas.add(t);
                planificacionReducida = true;
                s.solve();
                tiempoEjecucion += a.getExecutionTime();
                nodosExpandidos += a.getNodosExpandidos();
                variablesExpandidas += a.getVariablesExpandidas();
            }
            for (Tarea ti : tareasEliminadas)
                g.addNodo(ti);

            if (s.hasSolution()) {
                ((TransportesFrame)parent).presentPlanning(
                        tiempoEjecucion / 1000000000,
                        nodosExpandidos,
                        variablesExpandidas);
                if (planificacionReducida) {
                    JFrame frame = new JFrame();
                    JOptionPane.showMessageDialog(frame,
                            "Se ha tenido que reducir el número de tareas no programadas para poder realizar un horario correcto.",
                            "Nota",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            } else {
                JFrame frame = new JFrame();
                JOptionPane.showMessageDialog(frame,
                        "No se ha encontrado planificación posible.",
                        "Nota",
                        JOptionPane.INFORMATION_MESSAGE);
            }
            
        } catch (Exception e) {
            System.out.println("MVR Error: " + e.toString());
            // show error dialog
            JFrame frame = new JFrame();
            JOptionPane.showMessageDialog(frame,
                    "Debe añadir conductores y tareas antes de iniciar la planificación.",
                    "Atención",
                    JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnIniciarMouseReleased


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup bgAlgoritmos;
    private javax.swing.JButton btnIniciar;
    private javax.swing.JComboBox cbAlgoritmos;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables

}
